<script lang="ts">
import {Ref, ref, UnwrapRef, defineComponent, PropType} from "vue"

export default defineComponent({
  name: "DateRange",
  emits: {
    "change": (object: any) => true,
    "input": (object: any) => true,
    "update:modelValue": (object: any) => true
  },
  props: {
    modelValue: {
      type: Array as PropType<string[]>,
      default: true
    },
    completion: {//补全时间
      type: Boolean,
      default: true
    },
    clearable: {//补全时间
      type: Boolean,
      default: true
    },
    disabled: {//补全时间
      type: Boolean,
      default: false
    },
    startPlaceholder: {
      type: String,
      default: '开始日期'
    },
    endPlaceholder: {
      type: String,
      default: '结束日期'
    }
  },
  setup(props, {emit}) {
    //设置初始值
    const start: Ref<UnwrapRef<string | undefined>> = ref(props.modelValue[0] ? props.modelValue[0] : undefined)
    const end: Ref<UnwrapRef<string | undefined>> = ref(props.modelValue[1] ? props.modelValue[1] : undefined)

    /**
     * 值变化
     * @param value
     * @param key
     * @constructor
     */
    const ValueChange = function (value: string, key: string) {
      if (key === 'start') {
        const DataValue = [
          value ? (value + (props.completion ? ' 00:00:00' : '')) : '',
          end.value ? (end.value + (props.completion ? ' 23:59:59' : '')) : ''
        ]
        setValue(DataValue)
      } else if (key === 'end') {
        const DataValue = [
          start.value ? (start.value + (props.completion ? ' 00:00:00' : '')) : '',
          value ? (value + (props.completion ? ' 23:59:59' : '')) : ''
        ]
        setValue(DataValue)
      }
    }

    /**
     * 设置数据值
     */
    function setValue(DataValue) {
      emit('update:modelValue', DataValue)
      emit('change', DataValue)
      emit('input', DataValue)
    }

    return {
      start, end, ValueChange
    }
  }
})
</script>
<template>
  <div class="date-range el-input">
    <el-date-picker :disabled class="date-range-start" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :placeholder="startPlaceholder" v-model="start" @change="ValueChange($event,'start')" type="date" :clearable/>
    <el-date-picker :disabled class="date-range-end" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :placeholder="endPlaceholder" v-model="end" @change="ValueChange($event,'end')" type="date" :clearable/>
  </div>
</template>

<style scoped lang="scss">
.date-range {
  width: 100%;

  :deep(.date-range-start) {
    width: calc(50% - 2px);
    margin-right: 4px;
  }

  :deep(.date-range-end) {
    width: calc(50% - 2px);

    .el-input__wrapper {
      border-radius: var(--el-input-border-radius) !important;
    }
  }
}
</style>